package router

import (
	"database/sql"
	"gdshop-admin-go-api/app/controllers"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func regMember(s *ghttp.Server, versionName, defaultVersionName string) {
	// 路由前缀
	routerPrefix := "/member"
	s.Group(routerPrefix, func(group *ghttp.RouterGroup) {
		group.Middleware(MiddlewareIsMemberLogin)
		c := controllers.NewMemberController(&BaseReq.I{
			TableName:          "member",
			InfoIgnoreProperty: "password,password_salt,update_at,delete_at", // info 时过滤
			AddBeforeFn: func(r *ghttp.Request, data map[string]interface{}) *response.JsonResponse {
				if data["mobile"] == nil {
					return response.FailByRequestMessage(nil, "账号不能未空")
				}
				// 添加前，先判断手机号码是否存在
				ctx := r.GetCtx()
				memberDb := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member")
				memberModel := (*entity.Member)(nil)
				err := memberDb.Where(g.Map{
					"mobile": data["mobile"],
				}).Struct(&memberModel)
				if err != nil && err != sql.ErrNoRows {
					// 有错误，并且不是数据为空的错误，则返回
					return response.FailByRequestMessage(nil, err.Error())
				}
				if memberModel != nil {
					return response.FailByRequestMessage(nil, "账号已存在")
				}

				return response.SuccessByRequest(r)
			},
			UpdateIgnoreProperty: []string{ // update 时过滤
				"mobile",
				"password",
				"password_salt",
				"integral_coin",
				"money_coin",
			},
			PageQueryOp: &BaseReq.QueryOp{
				SelectFields: []string{
					"id",
					"mobile",
					"realname",
					"nickname",
					"status",
					"remark",
				},
				KeyWordLikeFields: g.ArrayStr{
					"mobile",
					"realname",
					"nickname",
				},
				FieldsEq: g.ArrayStr{
					"status",
				},
			},
		})
		controllerMaps := map[string]interface{}{
			"1.0.0": c,
		}
		// 权限判断
		group.Middleware(MiddlewareMemberPermissions)
		// 注册基础方法
		regBase([]string{
			"add",
			"delete",
			"update",
			"info",
			"list",
			"page",
		}, group, controllerMaps, versionName, defaultVersionName)

		group.POST("/reSetPwd", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "ReSetPwd")
		})
		group.POST("/setStatus", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "SetStatus")
		})
	})
}
